package net.scrumtool.controller;

import java.util.Date;
import java.util.List;

import net.scrumtool.model.Collaborator;
import net.scrumtool.model.Product;
import net.scrumtool.model.Sprint;
import net.scrumtool.model.Status;
import net.scrumtool.model.Userstory;
import net.scrumtool.technics.DAO;
import net.scrumtool.technics.LabelProviderOverviewSprint;
import net.scrumtool.view.Connexion;
import net.scrumtool.view.Home;
import net.scrumtool.view.OverviewSprint;
import net.scrumtool.view.Profile;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.MessageBox;

public class CoverviewSprint {
	OverviewSprint view;
	private Sprint sprintActif;
	private List<Userstory> usersstories;
	private Integer points;
	private Userstory usActif;

	public CoverviewSprint(OverviewSprint view) {
		this.view = view;
	}

	public void init(Sprint sprint) {
		setSprintActif(sprint);

		usersstories = DAO.getUsersStories(sprint);
		if (usersstories.size() > 0) {
			points = DAO.getPoints(usersstories);
		} else {
			points = 0;
		}

		view.getTltmEditUserStorySprint().setEnabled(false);
		view.getTltmRemoveUserStorySprint().setEnabled(false);
		view.getTltmEditBacklogUS().setEnabled(false);
		view.getTltmRemoveBacklogUS().setEnabled(false);

		view.getLblNameData().setText(sprint.getLabel());
		view.getLblProductData().setText(sprint.getProduct().getName());
		view.getLblPointsData().setText(points.toString());

		String dateStart = DAO.getDateOfSprint(sprint, "start").toString();
		String[] array = dateStart.split("-");
		dateStart = "" + array[2] + "/" + array[1] + "/" + array[0];
		view.getLblStartData().setText(dateStart);

		String dateEnd = DAO.getDateOfSprint(sprint, "end").toString();
		String[] array1 = dateEnd.split("-");
		dateEnd = "" + array1[2] + "/" + array1[1] + "/" + array1[0];
		view.getLblEndData().setText(dateEnd);

		view.getTableViewerUserStories().setContentProvider(new ArrayContentProvider());
		view.getTableViewerUserStories().setLabelProvider(new LabelProviderOverviewSprint());
		view.getTableViewerUserStories().setInput(usersstories);

		int percent = finishByPercent(usersstories);
		view.getPbSprint().setSelection(percent);
		view.getPbSprint().setToolTipText(percent + "%");
		view.getLblProgressBar().setText(percent + "% finished - " + dayLeft(sprint));

		view.getTableViewerBacklogUserStories().setContentProvider(new ArrayContentProvider());
		view.getTableViewerBacklogUserStories().setLabelProvider(new LabelProviderOverviewSprint());
		view.getTableViewerBacklogUserStories().setInput(usersstories);

		String[] arrayPriority = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
		view.getCbPriorityUS().setItems(arrayPriority);

		view.getCbViewerStatusUS().setContentProvider(new ArrayContentProvider());
		view.getCbViewerStatusUS().setInput(DAO.getStatus());
	}

	public void listener(final Collaborator collaborator) {

		// RETOUR VER HOME
		view.getBackToHome().addMouseListener(new MouseListener() {

			@Override
			public void mouseDoubleClick(
					org.eclipse.swt.events.MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseDown(org.eclipse.swt.events.MouseEvent arg0) {
				view.close();
				Home home = new Home();
				home.init();
				MainController mc = new MainController(home);
				mc.init(home);
				home.open();

			}

			@Override
			public void mouseUp(org.eclipse.swt.events.MouseEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		// PROFILE
		view.getLinkProfile().addMouseListener(new MouseListener() {

			@Override
			public void mouseDoubleClick(
					org.eclipse.swt.events.MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseDown(org.eclipse.swt.events.MouseEvent arg0) {
				Profile profile = new Profile();
				profile.init();
				Cprofile cProfile = new Cprofile(profile);
				cProfile.listener(collaborator, view.getLblInfoUser());
				cProfile.init(collaborator);
				profile.open();

			}

			@Override
			public void mouseUp(org.eclipse.swt.events.MouseEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		// LOGOUT
		view.getLinkSignout().addMouseListener(new MouseListener() {

			@Override
			public void mouseDoubleClick(
					org.eclipse.swt.events.MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseDown(org.eclipse.swt.events.MouseEvent arg0) {
				MessageBox messageBox = new MessageBox(view.getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
				messageBox.setText("SCRUMTOOL");
				messageBox.setMessage("Are you sure you want to exit ?");
				int response = messageBox.open();
				if (response == SWT.YES) {
					Connexion connexion = new Connexion();
					connexion.init();
					Cconnexion cConnexion = new Cconnexion(connexion);
					cConnexion.init();
					view.close();
					connexion.open();
				}
			}

			@Override
			public void mouseUp(org.eclipse.swt.events.MouseEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTableUserStories().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				view.getTltmEditUserStorySprint().setEnabled(true);
				view.getTltmRemoveUserStorySprint().setEnabled(true);
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTltmAddUserStorySprint().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				view.getTabFolderOverviewSprint().setSelection(1);
				view.getGrpBacklogUserStories().setText("Add");
				view.getTxtNameUS().setText("");
				view.getTxtDescrUS().setText("");
				view.getTxtPointsUS().setText("");
				view.getCbPriorityUS().setText("");
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTltmEditUserStorySprint().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {

				view.getTabFolderOverviewSprint().setSelection(1);
				view.getGrpBacklogUserStories().setText("Edit");
				StructuredSelection sel = (StructuredSelection) view.getTableViewerUserStories().getSelection();
				setUSActif((Userstory) sel.getFirstElement());

				enableFormUS(true);

				view.getTxtNameUS().setText(usActif.getLabel());
				view.getTxtDescrUS().setText(usActif.getDescription());
				view.getTxtPointsUS().setText(usActif.getStoryPoints().toString());
				view.getCbPriorityUS().setText(usActif.getPriority().toString());
				view.getCbViewerStatusUS().setSelection(new StructuredSelection(usActif.getStatus()));
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTltmRemoveUserStorySprint().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				StructuredSelection sel = (StructuredSelection) view.getTableViewerUserStories().getSelection();
				setUSActif((Userstory) sel.getFirstElement());

				DAO.SQLUserStory(usActif, "delete");

				usersstories.remove(usActif);
				view.getTableViewerBacklogUserStories().refresh();
				view.getTableViewerUserStories().refresh();
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTableBacklogUserStories().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				view.getTltmEditBacklogUS().setEnabled(true);
				view.getTltmRemoveBacklogUS().setEnabled(true);

				StructuredSelection sel = (StructuredSelection) view.getTableViewerBacklogUserStories().getSelection();
				setUSActif((Userstory) sel.getFirstElement());

				view.getGrpBacklogUserStories().setText("View");
				view.getTxtNameUS().setText(usActif.getLabel());
				view.getTxtDescrUS().setText(usActif.getDescription());
				view.getTxtPointsUS().setText(usActif.getStoryPoints().toString());
				view.getCbPriorityUS().setText(usActif.getPriority().toString());
				view.getCbViewerStatusUS().setSelection(new StructuredSelection(usActif.getStatus()));

				enableFormUS(false);
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getButValiderUS().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {

				Product product = sprintActif.getProduct();

				IStructuredSelection ss = (IStructuredSelection) view.getCbViewerStatusUS().getSelection();
				Status status = (Status) ss.getFirstElement();

				String label = view.getTxtNameUS().getText();
				String description = view.getTxtDescrUS().getText();

				String storyPointsS = view.getTxtPointsUS().getText();
				Integer storyPoints = Integer.parseInt(storyPointsS);

				String priorityS = view.getCbPriorityUS().getText();
				Integer priority = Integer.parseInt(priorityS);

				if (view.getGrpBacklogUserStories().getText() == "Add") {
					Userstory us = new Userstory(sprintActif, product, status, label, description, storyPoints, priority, null);

					DAO.SQLUserStory(us, "insert");

					usersstories.add(us);
				} else if (view.getGrpBacklogUserStories().getText() == "Edit") {
					usersstories.remove(usActif);

					usActif.setProduct(product);
					usActif.setStatus(status);
					usActif.setLabel(label);
					usActif.setDescription(description);
					usActif.setStoryPoints(storyPoints);
					usActif.setPriority(priority);

					DAO.SQLUserStory(usActif, "update");
					usersstories.add(usActif);

				}

				view.getTableViewerBacklogUserStories().refresh();
				view.getTableViewerUserStories().refresh();

			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTltmEditBacklogUS().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {

				view.getTabFolderOverviewSprint().setSelection(1);
				view.getGrpBacklogUserStories().setText("Edit");
				StructuredSelection sel = (StructuredSelection) view.getTableViewerBacklogUserStories().getSelection();
				setUSActif((Userstory) sel.getFirstElement());

				enableFormUS(true);

				view.getTxtNameUS().setText(usActif.getLabel());
				view.getTxtDescrUS().setText(usActif.getDescription());
				view.getTxtPointsUS().setText(usActif.getStoryPoints().toString());
				view.getCbPriorityUS().setText(usActif.getPriority().toString());
				view.getCbViewerStatusUS().setSelection(new StructuredSelection(usActif.getStatus()));
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTltmAddBacklogUS().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				view.getTabFolderOverviewSprint().setSelection(1);
				view.getGrpBacklogUserStories().setText("Add");
				view.getTxtNameUS().setText("");
				view.getTxtDescrUS().setText("");
				view.getTxtPointsUS().setText("");
				view.getCbPriorityUS().setText("");

				enableFormUS(true);
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		view.getTltmRemoveBacklogUS().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				StructuredSelection sel = (StructuredSelection) view.getTableViewerBacklogUserStories().getSelection();
				setUSActif((Userstory) sel.getFirstElement());

				DAO.SQLUserStory(usActif, "delete");

				usersstories.remove(usActif);
				view.getTableViewerBacklogUserStories().refresh();
				view.getTableViewerUserStories().refresh();

			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void enableFormUS(Boolean bool) {

		view.getTxtNameUS().setEnabled(bool);
		view.getTxtDescrUS().setEnabled(bool);
		view.getTxtPointsUS().setEnabled(bool);
		view.getCbPriorityUS().setEnabled(bool);
		view.getCbStatusUS().setEnabled(bool);
		view.getButValiderUS().setEnabled(bool);
	}

	public void setSprintActif(Sprint sprint) {
		this.sprintActif = sprint;
	}

	public void setUSActif(Userstory us) {
		this.usActif = us;
	}

	private int finishByPercent(List<Userstory> usersstories) {
		int n = 0;
		for (Userstory us : usersstories) {
			if (us.getStatus().getIdStatus() == 3) {
				n++;
			}
		}

		float percent = (float) n / usersstories.size();
		percent = percent * 100;
		int nb = (int) percent;
		return nb;
	}

	private String dayLeft(Sprint sprint) {
		final long MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
		long numberOfDay = 0;
		boolean isStart = false;
		String str = "";
		String unit = "";

		Date datestart = DAO.getDateOfSprint(sprint, "start");
		Date dateend = DAO.getDateOfSprint(sprint, "end");
		Date datenow = new Date();

		// Si le sprint est commencé
		if (datestart.compareTo(datenow) < 0) {
			isStart = true;
			// si le début est avant la fin
			if (datestart.compareTo(dateend) < 0) {
				long diff = Math.abs(dateend.getTime() - datestart.getTime());
				numberOfDay = (long) diff / MILLISECONDS_PER_DAY;
			}
		} else {
			isStart = false;
			long diff = Math.abs(datestart.getTime() - datenow.getTime());
			numberOfDay = (long) diff / MILLISECONDS_PER_DAY;
		}

		if (numberOfDay > 90) {
			long numberOfMonth = numberOfDay / 30;
			if (numberOfMonth > 12) {
				long numberOfYear = numberOfMonth / 12;
				if (numberOfYear > 1) {
					unit = "years";
				} else {
					unit = "year";
				}
				str = numberOfYear + "";
			} else {
				if (numberOfMonth > 1) {
					unit = "months";
				} else {
					unit = "month";
				}
				str = numberOfMonth + "";
			}
		} else {
			if (numberOfDay > 1) {
				unit = "days";
			} else {
				unit = "day";
			}
			str = numberOfDay + "";
		}

		if (isStart) {
			return str + " " + unit + " left";
		} else {
			return str + " " + unit + " before it begins";
		}

	}
}
